<?php

m2import('phpinchains/util/generator/DBGenerator.php');

class phpinchains_util_generator_PSPShowDBGenerator extends phpinchains_util_generator_DBGenerator {

    const pspcode = '%s
';

    public static function versionSelector ($table) {
        $usebundles = $GLOBALS['generatorCnf']['options']['use-bundles'];
        if (isset($GLOBALS['generatorCnf']['options']['versioned-table'][getTableName($table)])) {
        return '<form pspc="h:form" action="'.self::genActionMappingName($table).'::show">
    '.($usebundles?'<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="choose_version"/>:':'Version ausw&auml;hlen:').
   '<h:hidden name="selectversion" value="true"/>
    <h:hidden name="id" value="${sessionScope->selectedObj_'.strtolower($table).'_id}"/>
    <select pspc="h:selectBox" name="versiondate"
    selected="${fn:alt(versiondate, sessionScope[\''.strtolower($table).'_selectedVersion_\'.sessionScope->selectedObj_'.strtolower($table).'_id])}"
    optionvalue="'.$GLOBALS['generatorCnf']['options']['versioned-table'][getTableName($table)]['start'].'"
    optiontext="'.$GLOBALS['generatorCnf']['options']['versioned-table'][getTableName($table)]['start'].'"
    value="${versions}">
        <c:if test="${!versiondeleted}"><option value="">'.self::genBundleMessage($usebundles, 'none_chosen', 'Aktuelle Version').'</option></c:if>
    </select>
    <input type="submit" value="'.($usebundles?'<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="choose"/>':'Ausw&auml;hlen').'"/>
</form>
';
        }
    }

    public static function versionSelectorExecute ($table) {
        if (isset($GLOBALS['generatorCnf']['options']['versioned-table'][getTableName($table)])) {
        return '
        <c:execute action="'.self::genClassName($table).'Action::_versionSelector">
            <c:actionparam name="id" value="${fn:alt(id, displayObj->id)}"/>
        </c:execute>
';
        }
    }

    /**
     * Generates the code for the specified table information.
     *
     * @param string $table
     * @param array $rows
     */
    public static function generateCode ($table, $rows, $indexes = array()) {
        $usebundles = $GLOBALS['generatorCnf']['options']['use-bundles'];
        $cssfile    = $GLOBALS['generatorCnf']['options']['css-href'];

        $hideCreate  = (isset($GLOBALS['generatorCnf']['options']['hide-actions'][$table]['create']) && $GLOBALS['generatorCnf']['options']['hide-actions'][$table]['create'])
            || (isset($GLOBALS['generatorCnf']['options']['hide-action-buttons'][$table]['create']) && $GLOBALS['generatorCnf']['options']['hide-action-buttons'][$table]['create']);
        $hideEdit    = (isset($GLOBALS['generatorCnf']['options']['hide-actions'][$table]['edit']) && $GLOBALS['generatorCnf']['options']['hide-actions'][$table]['edit'])
            || (isset($GLOBALS['generatorCnf']['options']['hide-action-buttons'][$table]['edit']) && $GLOBALS['generatorCnf']['options']['hide-action-buttons'][$table]['edit']);
        $hideDelete  = (isset($GLOBALS['generatorCnf']['options']['hide-actions'][$table]['delete']) && $GLOBALS['generatorCnf']['options']['hide-actions'][$table]['delete'])
            || (isset($GLOBALS['generatorCnf']['options']['hide-action-buttons'][$table]['delete']) && $GLOBALS['generatorCnf']['options']['hide-action-buttons'][$table]['delete']);
        $hideShow    = (isset($GLOBALS['generatorCnf']['options']['hide-actions'][$table]['show']) && $GLOBALS['generatorCnf']['options']['hide-actions'][$table]['show'])
            || (isset($GLOBALS['generatorCnf']['options']['hide-action-buttons'][$table]['delete']) && $GLOBALS['generatorCnf']['options']['hide-action-buttons'][$table]['delete']);
        $hideListing = (isset($GLOBALS['generatorCnf']['options']['hide-actions'][$table]['listing']) && $GLOBALS['generatorCnf']['options']['hide-actions'][$table]['listing'])
            || (isset($GLOBALS['generatorCnf']['options']['hide-action-buttons'][$table]['delete']) && $GLOBALS['generatorCnf']['options']['hide-action-buttons'][$table]['delete']);

        $title = ($usebundles ? '<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="show_title"/>' : self::genClassName(str_replace('_', ' ', $table)).' Liste');
        $bundlecode = '<fmt:setLocale value="'.($GLOBALS['generatorCnf']['options']['locale']).'"/><fmt:loadBundle bundle="'.$table.'"/>'."\n";
        $code = ($usebundles?$bundlecode:'').'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset='.(getConfOption('encoding')?getConfOption('encoding'):'iso-8859-1').'" />
<meta http-equiv="content-language" content="de" />
<title>'.$title.'</title>
';
        $code .= self::getSnippet('head', $table);

        $code .= self::getSpecificSnippet('show', 'head', $table);

        if ($cssfile) {
            $code .= '<link rel="stylesheet" type="text/css" href="'.$cssfile.'"/>'."\n";
        }
        $code .= '
</head>
<body>
';
        $code .= self::getSnippet('top', $table);

        $code .= '            <h1 id="'.$table.'ShowTitle" class="showpspTitle">'.$title.'</h1>';

        $code .= self::getSpecificSnippet('show', 'top', $table);

        // Navigation
        $code .= '
        <div id="'.$table.'ShowNavi" class="showpspNavi">
            '.($hideEdit?'':'<c:url action="'.self::genActionMappingName($table).'::edit" var="editURL">
                <c:param name="id" value="${displayObj->id}"/>
                <c:param name="caller" value="show"/>
            '.(isset($GLOBALS['generatorCnf']['options']['versioned-table'][getTableName($table)])?'    <c:param name="versiondate" value="${sessionScope[\''.strtolower($table).'_selectedVersion_\'.sessionScope->selectedObj_'.strtolower($table).'_id]}"/>
            ':'').'</c:url>
            <a class="showNavEdit" href="${editURL}">'.($usebundles?'<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="edit"/>':'Bearbeiten').'</a>
            <span class="pspNaviSeparator">|</span>').'
            '.($hideListing?'':'<c:url action="${sessionScope->redirect_'.strtolower($table).'?sessionScope->redirect_'.strtolower($table).':\''.(isset($GLOBALS['generatorCnf']['options']['listing-action-override'][$table])?$GLOBALS['generatorCnf']['options']['listing-action-override'][$table]:self::genActionMappingName($table).'::listing').'\'}" var="listingURL">
            </c:url>
            <a class="showNavOverview" href="${listingURL}">'.($usebundles?'<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="to_overview"/>':'zur &Uuml;bersicht').'</a>').'
            '.(isset($GLOBALS['generatorCnf']['options']['action-buttons'][$table]['shownavi'])?$GLOBALS['generatorCnf']['options']['action-buttons'][$table]['shownavi']:'').'
        </div>
';

        // content table
        $code .='
        <div id="'.$table.'ShowData" class="showpspData">'."\n";
        $code .= self::versionSelectorExecute($table);
        $mixincode = self::getViewMixin($table, 'show');
        if ($mixincode) {
            $code .= $mixincode;
        } else {
            $code .= self::genShowTable($table, $usebundles, $rows);
        }

        $code .= '        </div>'."\n";
        $code .= self::getSpecificSnippet('show', 'bottom', $table);

        $code .= self::getSnippet('bottom', $table);

        $code .= '</body>
</html>';
        return array(sprintf(self::pspcode, $code), self::versionSelector($table));
    }

    /**
     * Saves the php to a php file.
     *
     * Adds code to a php block while saving.
     *
     * @param string $destfile File to save to. Is created, if not exists.
     * @param string $code     PHP code to save to the file.
     */
    public static function saveCode ($table, $destfile, $code, $force = false) {
        if (!file_exists(dirname($destfile)))
            mkdir(dirname($destfile));
        if ($force || !file_exists($destfile."/show.psp")) {
            print "create file '$destfile/show.psp'\n";
            file_put_contents($destfile."/show.psp", $code[0]);
        }
        if (($force || !file_exists($destfile."/_versionSelector.psp")) && $code[1]) {
            print "create file '$destfile/_versionSelector.psp'\n";
            file_put_contents($destfile."/_versionSelector.psp", $code[1]);
        }
    }

    public static function getHtml($table, $field, $part) {
       return strlen($GLOBALS['generatorCnf']['options']['show-table-html'][$table][$field][$part])?$GLOBALS['generatorCnf']['options']['show-table-html'][$table][$field][$part]:'';
    }

    public static function genShowTable ($table, $usebundles, & $rows) {
        $code =  '           <table id="'.$table.'ShowTable" class="showpspTable">'."\n";
        $count = 0;
        for ($i = 0; $i < count($rows);$i++) {
            $cssclass = ($count%2==1?'oddrow':'evenrow');
            $wrappingcode = array('<c:out value="', '"/>');
            if (is_array($GLOBALS['generatorCnf']['options']['show-value-wrap'][$table][$rows[$i][0]])) {
                $wrappingcode = $GLOBALS['generatorCnf']['options']['show-value-wrap'][$table][$rows[$i][0]];
            }
            if (getBySQLType($rows[$i][1]) == 'blob') {
                $code .= (self::getHtml($table, $rows[$i][0], 'top')?self::getHtml($table, $rows[$i][0], 'top'):'                <tr class="row-'.$rows[$i][0].'"><td class="'.$cssclass.' namecol">').($usebundles?'<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="'.$rows[$i][0].'"/>':self::upperFirstLetter(str_replace('_', ' ',$rows[$i][0])));
                $code .= ' ('.($usebundles?'<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="binary_data"/>':'Bin&auml;rdaten').')'.(self::getHtml($table, $rows[$i][0], 'between')?self::getHtml($table, $rows[$i][0], 'between'):':</td><td  class="'.$cssclass.' valcol">').'
                    <c:if test="${displayObj->'.$rows[$i][0].'}">
                        <c:url action="'.self::genActionMappingName($table).'::viewBlob" var="viewBlobURL">
                            <c:param name="id" value="${displayObj->id}"/>
                            <c:param name="field" value="'.$rows[$i][0].'"/>
                        </c:url>
                        <c:url action="'.self::genActionMappingName($table).'::downloadBlob" var="downloadBlobURL">
                            <c:param name="id" value="${displayObj->id}"/>
                            <c:param name="field" value="'.$rows[$i][0].'"/>
                        </c:url>
                        <c:if test="${fn:preg_match(\'/^image/\', displayObj->'.$rows[$i][0].'_type)}">
                            <img src="${viewBlobURL}" width="200"/><br/>
                            <c:else>
                                <a href="${viewBlobURL}" target="_blank">'.($usebundles?'<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="show_file"/>':'Datei anzeigen').'</a>
                            </c:else>
                        </c:if>
                        <a href="${downloadBlobURL}">'.($usebundles?'<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="download_file"/>':'Datei herunterladen').'</a>
                    </c:if>
                ';
                $code .= (self::getHtml($table, $rows[$i][0], 'bottom')?self::getHtml($table, $rows[$i][0], 'bottom'):'</td></tr>')."\n";
                $count++;
            } elseif (is_array($GLOBALS['generatorCnf']['tables'][$table][$rows[$i][0]])) {
                if ($rows[$i][0] == strtolower($table).'_parent_id') {
                    $fieldname = $rows[$i][0].'->'.$GLOBALS['generatorCnf']['tables'][$table][$rows[$i][0]][1];
                } else {
                    $fieldname = $GLOBALS['generatorCnf']['tables'][$table][$rows[$i][0]][1];
                }
                $code .= (self::getHtml($table, $rows[$i][0], 'top')?self::getHtml($table, $rows[$i][0], 'top'):'                <tr class="row-'.$rows[$i][0].'"><td class="'.$cssclass.' namecol">').($usebundles?'<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="'.$rows[$i][0].'"/>':self::upperFirstLetter(str_replace('_', ' ',$GLOBALS['generatorCnf']['tables'][$table][$rows[$i][0]][0])));
                $code .= ':</td><td class="'.$cssclass.' valcol">'./*'<a href="<c:url action="'.$GLOBALS['generatorCnf']['tables'][$table][$rows[$i][0]][0].
                    '::show"><c:param name="id" value="${displayObj->'.$rows[$i][0].'}"/></c:url>">'.*/$wrappingcode[0].'${displayObj->'.$fieldname."}".$wrappingcode[1];
                $code .= /*'</a>'.*/'</td></tr>'."\n";
                $count++;
            } elseif (empty($GLOBALS['generatorCnf']['tables'][$table][$rows[$i][0]])) {
                $code .= (self::getHtml($table, $rows[$i][0], 'top')?self::getHtml($table, $rows[$i][0], 'top'):'                <tr class="row-'.$rows[$i][0].'"><td class="'.$cssclass.' namecol">').($usebundles?'<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="'.$rows[$i][0].'"/>':self::upperFirstLetter(str_replace('_', ' ',$rows[$i][0])));
                $code .= (self::getHtml($table, $rows[$i][0], 'between')?self::getHtml($table, $rows[$i][0], 'between'):':</td><td class="'.$cssclass.' valcol">').$wrappingcode[0].'${displayObj->'.$rows[$i][0]."}".$wrappingcode[1];
                $code .= (self::getHtml($table, $rows[$i][0], 'bottom')?self::getHtml($table, $rows[$i][0], 'bottom'):'</td></tr>')."\n";
                $count++;
            }
        //$code .= "    <'{$rows[$i][0]}', '".getBySQLType($rows[$i][1])."')".($i == count($rows)-1?'':',')."\n";

        }
        $code .= '            </table>'."\n";
        return $code;
    }

}

?>